package com.hxs.learn.plugins.plugins.gen;

import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.db.MetadataManager;
import org.beetl.sql.core.db.TableDesc;
import org.beetl.sql.core.kit.GenKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileWriter;
import java.util.List;
import java.util.Map;

public class AutoGen {
    private static Logger logger = LoggerFactory.getLogger(AutoGen.class);

    /**
     * 一步完成所有代码生成
     */
    public static void go(SQLManager sqlManager, String project, String basepkg, String moduleName, String table) {
        GenConfig config = new GenConfig();
        config.codeGens.add(new MapperCodeGen(basepkg, moduleName));
        config.codeGens.add(new ServiceCodeGen(basepkg, moduleName));
        String srcPath = getPath(project, "/src/main/java");
        String pkg = basepkg + ".entity";
        if (null != moduleName && moduleName.length() > 0) {
            pkg = basepkg + ".entity." + moduleName;
        }
        SourceGen gen = new SourceGen(sqlManager, table, pkg, moduleName, srcPath, config);
        pkg = basepkg + ".mapper";
        if (null != moduleName && moduleName.length() > 0) {
            pkg = basepkg + ".mapper." + moduleName;
        }
        try {
            gen.gen();
            genSQLFile(sqlManager, pkg, moduleName, table, project, gen.get_attrs());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error("自动生成代码失败", e);
        }
    }

    /**
     * 一步完成所有代码生成
     */
    public static void go(SQLManager sqlManager, String project, String basepkg, String moduleName, List<String> tables) {
        if (!CollectionUtils.isEmpty(tables)) {
            for (String table : tables) {
                go(sqlManager, project, basepkg, moduleName, table);
            }
        }
    }

    public static void genPojo(SQLManager sqlManager, String project, String basepkg, String moduleName, String table) {
        GenConfig config = new GenConfig();
        String srcPath = getPath(project, "/src/main/java");
        String pkg = basepkg + ".entity";
        if (null != moduleName && moduleName.length() > 0) {
            pkg = basepkg + ".entity." + moduleName;
        }
        SourceGen gen = new SourceGen(sqlManager, table, pkg, moduleName, srcPath, config);
        try {
            gen.gen();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void genPojoDao(SQLManager sqlManager, String project, String basepkg, String moduleName, String table) {
        GenConfig config = new GenConfig();
        config.codeGens.add(new MapperCodeGen(basepkg, moduleName));
        String srcPath = getPath(project, "/src/main/java");
        String pkg = basepkg + ".entity";
        if (null != moduleName && moduleName.length() > 0) {
            pkg = basepkg + ".entity." + moduleName;
        }
        SourceGen gen = new SourceGen(sqlManager, table, pkg, moduleName, srcPath, config);
        try {
            gen.gen();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void genPojoDaoService(SQLManager sqlManager, String project, String basepkg, String moduleName, String table) {
        GenConfig config = new GenConfig();
        config.codeGens.add(new MapperCodeGen(basepkg, moduleName));
        config.codeGens.add(new ServiceCodeGen(basepkg, moduleName));
        String srcPath = GenKit.getJavaSRCPath();
        String pkg = basepkg + ".entity";
        if (null != moduleName && moduleName.length() > 0) {
            pkg = basepkg + ".entity." + moduleName;
        }
        SourceGen gen = new SourceGen(sqlManager, table, pkg, moduleName, srcPath, config);
        try {
            gen.gen();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private static String getPath(String project, String relativeToSrc) {
        String srcPath;
        String userDir = System.getProperty("user.dir");
        if (userDir == null) {
            throw new NullPointerException("用户目录未找到");
        }
        File src = new File(userDir);
        String parent = src.getParent();

        File resSrc = new File(parent + "/" + project, relativeToSrc);
        if (resSrc.exists()) {
            srcPath = resSrc.toString();
        } else {
            srcPath = src.toString();
        }
        return srcPath;
    }

    /**
     * 生成sql文件
     *
     * @param sqlManager
     * @param table
     * @throws Exception
     */
    private static void genSQLFile(SQLManager sqlManager, String pkg, String moduleName, String table, String project, List<Map> attrs) throws Exception {
        String path = "/mappers/" + moduleName;
        String srcPath = getPath(project, "/src/main/resources");
        MetadataManager mm = sqlManager.getMetaDataManager();
        final TableDesc tableDesc = mm.getTable(table);

        String entityClass = sqlManager.getNc().getClassName(tableDesc.getName());
        String mapperClass = entityClass + "Mapper";

        String target = srcPath + path + "/" + mapperClass + ".xml";
        File mdfile = new File(target);
        if (mdfile.exists()) {
            logger.info("文件已存在，不生成！");
        } else {
            File sqlfile = new File(srcPath + path);
            if (!sqlfile.exists()) {
                sqlfile.mkdirs();
            }
            FileWriter writer = new FileWriter(mdfile);
            MdCodeGen gen = new MdCodeGen();
            gen.genCode(sqlManager, pkg, table, writer, attrs);
            writer.close();
            logger.info("gen \"" + table + "\" success at " + target);
        }
    }
}
